<template>
  <a-select v-bind="$attrs" :disabled="readonly" v-model="currentValue" :placeholder="placeholder" @change="handleChange" filterable style="width:100%">
    <a-select-option v-for="item in options" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
  </a-select>
</template>

<script>
import { markeTypeSelector } from '@/api/meta'
export default {
  props: {
    value: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    classify: {
      type: String,
      default: '2'
    },
    parentId: {
      type: [String, Number],
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    },
    productCode: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      options: [],
      currentValue: this.value,
      loading: false,
    }
  },
  mounted () {
    this.loadData()
  },
  methods: {
    handleChange (val) {
      this.options.forEach(v => {
        if (v.code == val) {
          this.$emit('change', v)
        }
      })
      if (!val) this.$emit('change', {})
      this.$emit('input', val)
    },
    loadData () {
      const self = this
      const { classify, productCode } = this
      self.loading = true
      markeTypeSelector({ classify, product_code: productCode })
        .then((res) => {
          self.loading = false
          self.options = res.data
          self.currentValue = self.value
        })
        .catch(() => {
          self.loading = false
        })
    },
  },

  watch: {
    value: {
      immediate: true,
      handler (val) {
        this.currentValue = val + ''
      }
    },
    classify (val) {
      if (val) {
        this.loadData()
      }
    },
    productCode: {
      immediate: true,
      handler (val, old) {
        if (val != old) {
          this.loadData()
        }
      }
    }
  },
}
</script>

<style lang="less"></style>
